package com.jl.shudu.activity

import android.text.TextUtils
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.SaveListener
import com.admin.inspecting.until.SharedPreferencesUntil
import com.jl.shudu.R
import com.jl.shudu.base.BaseActivity
import com.jl.shudu.table.User
import com.jl.shudu.utils.Constant
import com.jl.shudu.utils.RegexUtils
import kotlinx.android.synthetic.main.activity_register.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

/**
 * 作者： 吴昶 .
 * 时间: 2018/12/3 17:46
 * 功能简介：
 */
class RegisterActivity:BaseActivity(){
    override fun bindLayout(): Int {
        return R.layout.activity_register
    }

    override fun initData() {
        tv_register_title.setCallBackListener { finish() }
    }

    override fun initEvent() {
        btn_register.setOnClickListener {
            val username=edt_user_name.text.toString()
            if(TextUtils.isEmpty(username)||username.length<4 || username.length>32){
                toast("用户名必须在 4 至 30 位之间")
                return@setOnClickListener
            }
            val password=edt_user_password.text.toString()
            if(TextUtils.isEmpty(password)||password.length<8 || password.length>16){
                toast("密码必须在 8 至 16 位之间")
                return@setOnClickListener
            }
            val phone=edt_user_phone.text.toString()
            if(TextUtils.isEmpty(phone)){
                toast("请输入手机号")
                return@setOnClickListener
            }
            if(!RegexUtils.isMobileExact(phone)){
                toast("手机号码错误")
                return@setOnClickListener
            }
            val secret=edt_user_secret.text.toString()
            if(TextUtils.isEmpty(secret)){
                toast("请输入保密口令，用于找回密码")
                return@setOnClickListener
            }
            val user=User()
            user.username=username
            user.setPassword(password)
            user.phone=phone
            user.secret=secret
            user.signUp(object :SaveListener<User>(){
                override fun done(p0: User?, p1: BmobException?) {
                    if(p1==null){
                        SharedPreferencesUntil.saveValue(Constant.USER_NAME,p0!!.username)
                        SharedPreferencesUntil.saveValue(Constant.USER_ID,p0.objectId)
                        startActivity<MainActivity>()
                        finish()
                        activity!!.finish()
                    }else{
                        toast(p1.message!!)
                    }
                }

            })
        }
    }


    companion object {
        var activity:LoginActivity?=null
        fun startRegisterActivity(activity: LoginActivity){
            this.activity=activity
            activity.startActivity<RegisterActivity>()
        }
    }
}